<template>
  <div class="rule-info pad">
    <el-page-header class="page-header" @back="goBack" :content="title">
    </el-page-header>
    <div class="head">
      <span>{{ruleNames[type - 1].label}}</span>
      <el-button @click="openDialog" type="primary" icon="el-icon-plus" circle></el-button>
    </div>
    <el-upload
      v-if="type !== '1'"
      action="http://localhost:8080/result/symptom/relation/batch"
      :http-request="handleUpload"
      :before-upload="beforeUpload"
      :show-file-list="false"
    >
      <el-button type="primary">批量上传</el-button>
    </el-upload>
    <div class="age-section m-t-b">
      <span class="age-title">年龄区间:</span>
      <el-input style="width: 120px;" readonly v-model="ageSection[0]">
        <span slot="append">岁</span>
      </el-input>
      <span style="padding: 0 30px;">-</span>
      <el-input style="width: 120px;" readonly v-model="ageSection[1]">
        <span slot="append">岁</span>
      </el-input>
    </div>
    <el-table class="m-t-b" stripe border :data="tabData" v-loading="loading">
      <el-table-column v-if="type === '1'" label="指标">
        <template slot-scope="scope">
          {{indexs[scope.row.type - 1].label}}
        </template>
      </el-table-column>
      <el-table-column v-if="type === '1'" label="Z评分" prop="pointRange">
      </el-table-column>
      <el-table-column v-if="type === '1'" label="结果" prop="result">
      </el-table-column>
      <el-table-column v-if="type === '2'" label="结果" prop="result">
      </el-table-column>
      <el-table-column v-if="type === '2'" label="症状" prop="symptom">
      </el-table-column>
      <el-table-column v-if="type === '2'" label="描述" prop="description">
      </el-table-column>
      <el-table-column v-if="type === '2'" label="权重值" prop="weight">
      </el-table-column>
      <el-table-column v-if="type === '3'" label="缺乏症" prop="ageusia">
      </el-table-column>
      <el-table-column v-if="type === '3'" label="症状" prop="symptom">
      </el-table-column>
      <el-table-column v-if="type === '3'" label="描述" prop="description">
      </el-table-column>
      <el-table-column v-if="type === '3'" label="权重值" prop="weight">
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button @click="updateRule(scope.row)" type="default" circle icon="el-icon-edit"></el-button>
          <el-button @click="deleteRule(scope.row)" type="danger" circle icon="el-icon-delete"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="m-t-b flex"
      :page-size="pageSize"
      layout="prev, pager, next"
      :current-page="curPage"
      @current-change="handlePagi"
      :total="total">
    </el-pagination>
    <!-- Z评分 -->
    <el-dialog v-if="type === '1'" :title="zDialogTitle" :visible.sync="showZDialog">
      <el-form :model="zGrade" label-position="top" ref="zGrade" :rules="rules">
        <el-form-item label="指标">
          <el-select v-model="zGrade.index">
            <el-option v-for="(item, i) in indexs" :label="item.label" :value="item.value" :key="i"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Z评分">
          <el-input type="number" v-model="zGrade.z">
            <el-select slot="prepend" style="width: 80px;" v-model="zGrade.range">
              <el-option value=">" label="大于"></el-option>
              <!-- <el-option value="=" label="等于"></el-option> -->
              <el-option value="<" label="小于"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="结果" prop="result">
          <el-select filterable v-model="zGrade.result">
            <el-option v-for="(item, i) in results" :label="item.result" :value="item.resultId" :key="i"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideZDialog">取 消</el-button>
        <el-button type="primary" @click="addZ('zGrade')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加结果症状设置页面 -->
    <el-dialog v-if="type === '2'" :title="descDialogTitle" :visible.sync="showDescDialog">
      <el-form :model="desc" ref="desc" :rules="rules">
        <el-form-item label="结果" prop="result">
          <el-select filterable v-model="desc.result">
            <el-option v-for="(item, i) in results" :label="item.result" :value="item.resultId" :key="i"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="症状" prop="symptom">
          <el-select filterable v-model="desc.symptom">
            <el-option v-for="(item, i) in symptoms" :label="item.symptomZ" :value="item.symptomId" :key="i"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-select filterable v-model="desc.description">
            <el-option v-for="(item, i) in descriptions" :label="item.descriptionZ" :value="item.descriptionId" :key="i"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权重值">
          <el-input-number v-model="desc.weight" :min="0" :max="100"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideDescDialog">取 消</el-button>
        <el-button type="primary" @click="addDesc('desc')">确 定</el-button>
      </div>
    </el-dialog>
     <!-- 添加缺乏症状设置页面 -->
    <el-dialog v-if="type === '3'" :title="lackDialogTitle" :visible.sync="showLackDialog">
      <el-form :model="lack" ref="lack" :rules="rules">
        <el-form-item label="缺乏症" prop="ageusiaId">
          <el-select filterable v-model="lack.ageusia">
            <el-option v-for="(item, i) in lackss" :label="item.ageusiaZ" :value="item.ageusiaId" :key="i"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="症状" prop="symptom">
          <el-select filterable v-model="lack.symptom">
            <el-option v-for="(item, i) in symptoms" :label="item.symptomZ" :value="item.symptomId" :key="i"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-select filterable v-model="lack.description">
            <el-option v-for="(item, i) in descriptions" :label="item.descriptionZ" :value="item.descriptionId" :key="i"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权重值">
          <el-input-number :min="0" :max="100" v-model="lack.weight"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideLackDialog">取 消</el-button>
        <el-button type="primary" @click="addLack('lack')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { excel2Json } from '../util';
import { addResultSymptomList, addLackSymptomResultList } from '../api';

import {
  addZPointResult,
  getAllResultList,
  getAllSymptom,
  getAllDescription,
  getAllLackList,
  deleteZPointResult,
  updateZPointResult,
  getZPointResultList,
  getResultSymptomList,
  addResultSymptom,
  deleteResultSymptom,
  updateResultSymptom,
  getLackSymptomResultList,
  addLackSymptomResult,
  deleteLackSymptomResult,
  updateLackSymptomResult
} from '../api'
import { notifySuccess } from '../util'

export default {
  name: 'rule-info',
  props: ['type', 'id', 'max', 'min'],
  data () {
    return {
      ruleNames: [
        { value: 1, label: 'Z评分设置' },
        { value: 2, label: '结果症状设置' },
        { value: 3, label: '缺乏症设置' }
      ],
      title: '',
      rules: {
        ageusia: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        result: [
          { required: true, message: '该项不能为空', trigger: 'change' }
        ],
        symptom: [
          { required: true, message: '该项不能为空', trigger: 'change' }
        ],
        description: [
          { required: true, message: '该项不能为空', trigger: 'change' }
        ]
      },
      loading: true,
      pageSize: 10,
      curPage: 1,
      total: 0,
      showZDialog: false,
      showDescDialog: false,
      showLackDialog: false,
      zDialogTitle: '添加Z评分设置',
      descDialogTitle: '添加结果症状设置',
      lackDialogTitle: '添加缺乏症症状描述关系',
      tabData: [],
      results: [],
      ageSection: [this.min, this.max],
      indexs: [{
        value: 1,
        label: '年龄别身高'
      }, {
        value: 2,
        label: '年龄别体重'
      }, {
        value: 3,
        label: '身高别体重'
      }],
      symptoms: [],
      lackss: [],
      descs: [
        '不爱吃东西、挑食',
        '皮肤苍白、没有精神头、经常犯困、经常感觉累、不爱动、头晕、呼吸急促',
        '消瘦',
        '嘴角潮红、嘴角起泡、舌头表面发红、舌头表面变光滑'
      ],
      z: [],
      zGrade: {
        index: 1,
        range: '>',
        z: '0',
        result: ''
      },
      descriptions: [],
      desc: {
        result: '',
        symptom: '',
        description: '',
        weight: 0
      },
      lacks: Array(10).fill({ // 缺乏症设置
        lack: '维生素A缺乏',
        symptom: '夜盲症',
        desc: '晚上看不清东西',
        weight: 3,
        ageSection: [3, 8]
      }),
      lack: {
        ageusia: '',
        symptom: '',
        description: '',
        weight: ''
      }
    }
  },
  methods: {
    beforeUpload (file) {
      const that = this;
      let type = file.name.split('.').pop();
      let isExcel = type === 'xlsx';
      if (!isExcel) {
        this.$message.error('只能上传Excel!')
      } else {
        excel2Json(file, this.$xlsx, function (worker, data) {
          if (!data.length) {
            return this.$message.error('文件读取失败！')
          }
          if (Number(that.type) === 2) {
            let list = data.map(item => {
              return {
                evaluationSettingId: Number(that.id),
                result: item.result,
                symptom: item.symptom,
                description: item.description,
                weight: item.weight
              }
            });
            addResultSymptomList(list)
            .then(res => {
              if (res.data.code === 1) {
                that.fetchResultSymptom(1);
                that.$message({
                  type: 'success',
                  message: '操作成功!'
                })
              } else {
                that.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              that.$message.error('网络异常!')
            })
          } else if (Number(that.type) === 3) {
            let list = data.map(item => {
              return {
                evaluationSettingId: that.id,
                ageusia: item.ageusia,
                symptom: item.symptom,
                description: item.description,
                weight: item.weight
              }
            });
            addLackSymptomResultList(list)
            .then(res => {
              if (res.data.code === 1) {
                that.fetchLackSymptomResult(1);
                that.$message({
                  type: 'success',
                  message: '操作成功!'
                })
              } else {
                that.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              that.$message.error('网络异常!')
            })
          }
        })
      };
      return isExcel
    },
    handleUpload () {
      console.log(arguments)
    },
    goBack () {
      history.back()
    },
    updateRule (data) {
      if (this.type === '1') {
        this.zDialogTitle = '修改Z评分设置'
        this.zGrade.index = data.type
        this.zGrade.range = data.pointRange[0]
        this.zGrade.z = data.pointRange.slice(1)
        this.zGrade.result = data.resultId
        this.zGrade.pointResultId = data.pointResultId
        this.showZDialog = true
      } else if (this.type === '2') {
        this.descDialogTitle = '修改结果症状设置'
        this.desc.result = data.resultId
        this.desc.description = data.descriptionId
        this.desc.symptom = data.symptomId
        this.desc.weight = data.weight
        this.desc.resultSymptomRelationId = data.resultSymptomRelationId
        this.showDescDialog = true
      } else if (this.type === '3') {
        this.lackDialogTitle = '修改缺乏症症状描述关系'
        this.lack.ageusia = data.ageusiaId
        this.lack.symptom = data.symptomId
        this.lack.description = data.descriptionId
        this.lack.weight = data.weight
        this.lack.ageusiaSymptomRelationId = data.ageusiaSymptomRelationId
        this.showLackDialog = true
      }
    },
    handlePagi (page) { // 分页
      if (this.type === '1') {
        this.fetchZGradeList(page)
      } else if (this.type === '2') {
        this.fetchResultSymptom(page)
      } else if (this.type === '3') {
        this.fetchLackSymptomResult(page)
      }
    },
    deleteRule (data) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.type === '1') {
          deleteZPointResult(data.pointResultId)
          .then(res => {
            if (res.data.code === 1) {
              notifySuccess(this)
              this.fetchZGradeList(1)
            } else {
              this.$message.error(res.data.msg || '网络异常!')
            }
          })
          .catch(e => {
            this.$message.error('网络异常!')
          })
        } else if (this.type === '2') {
          deleteResultSymptom(data.resultSymptomRelationId)
          .then(res => {
            if (res.data.code === 1) {
              notifySuccess(this)
              this.fetchResultSymptom(1)
            } else {
              this.$message.error(res.data.msg || '网络异常!')
            }
          })
          .catch(e => {
            this.$message.error('网络异常!')
          })
        } else if (this.type === '3') {
          deleteLackSymptomResult(data.ageusiaSymptomRelationId)
          .then(res => {
            if (res.data.code === 1) {
              notifySuccess(this)
              this.fetchLackSymptomResult(1)
            } else {
              this.$message.error(res.data.msg || '网络异常!')
            }
          })
          .catch(e => {
            this.$message.error('网络异常!')
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    hideZDialog () {
      this.showZDialog = false
    },
    addZ (form) { // 添加/修改z评分
      this.$refs[form].validate(valid => {
        if (valid) {
          if (this.zDialogTitle === '修改Z评分设置') {
            updateZPointResult({
              pointResultId: this.zGrade.pointResultId,
              resultId: this.zGrade.result,
              pointRange: this.zGrade.range + this.zGrade.z,
              type: this.zGrade.index
            })
            .then(res => {
              if (res.data.code === 1) {
                notifySuccess(this)
                this.showZDialog = false
                this.fetchZGradeList(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          } else {
            addZPointResult({
              resultId: this.zGrade.result,
              pointRange: this.zGrade.range + this.zGrade.z,
              type: this.zGrade.index,
              evaluationSettingId: this.id
            })
            .then(res => {
              if (res.data.code === 1) {
                notifySuccess(this)
                this.showZDialog = false
                this.fetchZGradeList(1)
              } else {
                this.$message.error(res.data.msg || '网络异常')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    openDialog () {
      let type = Number(this.type)
      switch (type) {
        case 1:
          this.zGrade.index = ''
          this.zGrade.z = ''
          this.zGrade.result = ''
          this.$nextTick(()=>{
            this.$refs['zGrade'].clearValidate()
          })
          this.zDialogTitle = '添加Z评分设置'
          this.showZDialog = true
          break
        case 2:
          this.desc.result = ''
          this.desc.symptom = ''
          this.desc.description = ''
          this.desc.weight = ''
          this.$nextTick(()=>{
            this.$refs['desc'].clearValidate()
          })
          this.descDialogTitle = '添加结果症状设置'
          this.showDescDialog = true
          break
        case 3:
          this.lack.ageusia = ''
          this.lack.symptom = ''
          this.lack.description = ''
          this.lack.weight = ''
          this.lackDialogTitle = '添加缺乏症症状描述关系'
          this.showLackDialog = true
          this.$nextTick(()=>{
            this.$refs['lack'].clearValidate()
          })
          break
        default:
          break
      }
    },
    hideDescDialog () {
      this.showDescDialog = false
    },
    addDesc (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if (this.descDialogTitle === '修改结果症状设置') {
            updateResultSymptom({
              resultSymptomRelationId: this.desc.resultSymptomRelationId, //  (Long)
              resultId: this.desc.result, //  //结果id  (Long)
              symptomId: this.desc.symptom, //  //症状id  (Long)
              descriptionId: this.desc.description, //  //描述id  (Long)
              weight: this.desc.weight, //  //权重  (Integer)
              evaluationSettingId: this.id, //  //健康评测设置id  (Long)
            })
            .then(res => {
              if (res.data.code === 1) {
                notifySuccess(this)
                this.showDescDialog = false
                this.fetchResultSymptom(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          } else {
            addResultSymptom({
              resultId: this.desc.result,
              symptomId: this.desc.symptom,
              descriptionId: this.desc.description,
              weight: this.desc.weight,
              evaluationSettingId: this.id,
            })
            .then(res => {
              if (res.data.code === 1) {
                notifySuccess(this)
                this.showDescDialog = false
                this.fetchResultSymptom(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    hideLackDialog () {
      this.showLackDialog = false
    },
    addLack (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if (this.lackDialogTitle === '修改缺乏症症状描述关系') {
            updateLackSymptomResult({
              ageusiaSymptomRelationId: this.lack.ageusiaSymptomRelationId,
              ageusiaId: this.lack.ageusia,
              symptomId: this.lack.symptom,
              descriptionId: this.lack.description,
              weight: this.lack.weight,
              evaluationSettingId: this.id,
            })
            .then(res => {
              if (res.data.code === 1) {
                notifySuccess(this)
                this.showLackDialog = false
                this.fetchLackSymptomResult(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          } else {
            addLackSymptomResult({
              ageusiaId: this.lack.ageusia,
              symptomId: this.lack.symptom,
              descriptionId: this.lack.description,
              weight: this.lack.weight,
              evaluationSettingId: this.id
            })
            .then(res => {
              if (res.data.code === 1) {
                notifySuccess(this)
                this.showLackDialog = false
                this.fetchLackSymptomResult(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    fetchQuestions () { // 获取所有结果
      getAllResultList()
      .then(res => {
        if (res.data.code === 1) {
          this.results = res.data.data || []
        } else {
          this.$message.error('网络错误!')
        }
      })
      .catch(e => {
        this.$message.error('网络错误!')
      })
    },
    fetchZGradeList (index) { // 获取z评分列表
      this.loading = true
      getZPointResultList({
        index,
        count: this.pageSize,
        queryParam: {
          evaluationSettingId: this.id
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          this.total = res.data.data.totalRecord
          this.tabData = res.data.data.list || []
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
        this.loading = false
      })
      .catch(e => {
        this.loading = false
        this.$message.error('网络异常!')
      })
    },
    fetchAllSymptom () { // 获取所有症状
      getAllSymptom()
      .then(res => {
        if (res.data.code === 1) {
          this.symptoms = res.data.data || []
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    fetchAllDescription () { // 获取所有描述
      getAllDescription()
      .then(res => {
        if (res.data.code === 1) {
          this.descriptions = res.data.data || []
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    fetchResultSymptom (index) { // 获取结果症状描述列表
      this.loading = true
      getResultSymptomList({
        index,
        count: this.pageSize,
        queryParam: {
          evaluationSettingId: this.id
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          this.total = res.data.data.totalRecord
          this.tabData = res.data.data.list || []
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
        this.loading = false
      })
      .catch(e => {
        this.loading = false
        this.$message.error('网络异常!')
      })
    },
    fetchAllLack () { // 获取所有的缺乏症
      getAllLackList()
      .then(res => {
        if (res.data.code === 1) {
          this.lackss = res.data.data || []
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    fetchLackSymptomResult (index) { // 获取缺乏症症状描述列表
      this.loading = true
      getLackSymptomResultList({
        index,
        count: this.pageSize,
        queryParam: {
          evaluationSettingId: this.id
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          this.total = res.data.data.totalRecord
          this.tabData = res.data.data.list
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
        this.loading = false
      })
      .catch(e => {
        this.loading = false
        this.$message.error('网络异常!')
      })
    }
  },
  created () {
    let path = this.$route.meta.path
    this.title = path[path.length - 1]
    let type = Number(this.type)
    switch (type) {
      case 1:
        this.fetchQuestions()
        this.fetchZGradeList(1)
        break
      case 2:
        this.fetchAllSymptom()
        this.fetchAllDescription()
        this.fetchQuestions()
        this.fetchResultSymptom(1)
        break
      case 3:
        this.fetchAllSymptom()
        this.fetchAllLack()
        this.fetchAllDescription()
        this.fetchLackSymptomResult(1)
        break
      default:
        break
    }
  }
}
</script>
<style lang="scss">
  .rule-info {
    .age-section {
      .age-title {
        padding-right: 20px;
      }
    }
    table {
      .cell {
        text-align: center;
      }
    }
  }
</style>
